package top.qingyunge.autumn.util.excelUtil;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import top.qingyunge.autumn.pojo.Sentence;
import top.qingyunge.autumn.service.SentenceService;

import java.util.*;

/**
 * @author zhangyouwei
 * @ 2021年05月08日22:44
 */
public class ExcelListener extends AnalysisEventListener<Sentence> {
    private final SentenceService sentenceService;
    //缓冲量（每100个数据提交一次数据库并清空缓存）
    private static final int BATCH_COUNT = 100;
    int count = 0;
    public ExcelListener(SentenceService sentenceService) {
        this.sentenceService = sentenceService;
    }
    public Map<Object, Object> map = new HashMap<>();
    List<Sentence> list = new ArrayList<>();
    /**
     * 这个每一条数据解析都会来调用
     *
     */
    @Override
    public void invoke(Sentence sentence, AnalysisContext analysisContext) {
        //已经发现错误
        if(!map.isEmpty()) return;
        //无错误继续
        count+=1;
        if(sentence.getSentence() == null || sentence.getSentence().isEmpty()) {
            map.put("msg","第"+(1+count) +"行句子不存在！");
            return ;
        }
        if(sentence.getType() == null) {
            map.put("msg","第"+(1+count) +"行未标明类型！");
            return ;
        }

        sentence.setCreateTime(new Date());
        sentence.setUpdateTime(new Date());

        list.add(sentence);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止大量数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }
    /**
     * 所有数据解析完成了会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }
    /**
     * 加上存储数据库
     */
    private void saveData() {
        if(map.isEmpty())
            sentenceService.saveBatch(list);
    }
}
